package com.johnny.bootlaunch.config;

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.Validator;

@Configuration
public class ValidatorConfiguration {
    /**
     *     增加下面的配置快速失败返回模式（只要有一个验证失败，则返还）
     *
     */
    @Bean
    public Validator validator(){
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .addProperty("hibernate.validator.fail_fast","true")
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor(){
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        /** 设置validator模式为快速失败返回 **/
        postProcessor.setValidator(validator());
        return postProcessor;
    }

    @Bean
    public ParamValidator paramValidator(){
        ParamValidator paramValidator = new ParamValidator(validator());
        return paramValidator;
    }
}
